package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.SequenceCriteria;
import com.leo.ibatis.demo.dao.SequenceDao;
import com.leo.ibatis.demo.domain.Sequence;
import com.leo.ibatis.demo.util.Paging;

public class SequenceDaoImpl extends SqlMapClientDaoSupport implements SequenceDao {

	public void insert(Sequence sequence) throws DataAccessException {
		getSqlMapClientTemplate().insert("Sequence.insert", sequence);
	}

	public int update(Sequence sequence) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Sequence.update", sequence, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String name) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Sequence.delete", name, actualRowsAffected);

		return actualRowsAffected;
	}

	public Sequence select(String name) throws DataAccessException {
		return (Sequence) getSqlMapClientTemplate().queryForObject("Sequence.select", name);
	}

	@SuppressWarnings("unchecked")
	public List<Sequence> list(SequenceCriteria sequenceCriteria) throws DataAccessException {
		Assert.notNull(sequenceCriteria, "sequenceCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Sequence.list", sequenceCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Sequence> listOnPage(SequenceCriteria sequenceCriteria) throws DataAccessException {
		Assert.notNull(sequenceCriteria, "sequenceCriteria must not be null");
		Assert.notNull(sequenceCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(sequenceCriteria);
		Paging paging = sequenceCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Sequence.list", sequenceCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(SequenceCriteria sequenceCriteria) throws DataAccessException {
		Assert.notNull(sequenceCriteria, "sequenceCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Sequence.count", sequenceCriteria)).intValue();
	}

}
